<template>
	<div class='login_container'>
		<div class='flex_center'>
			<div class='login_panel'>
				<div class='flex_center'>
					<div class='login_form'>
						<div class='please_login_text'>
							<h4>
								<!--<img alt='logo' src='../assets/login/images/logo.png'/>-->
								<!--嗷呜喵管理系统-->
							</h4>
							<span>
								欢迎登录
							</span>
						</div>
						<n-form
							ref='formRef'
							v-bind='formConfig' :model='formData' :rules='formRules'>
							<n-grid :y-gap='24' :cols='1'>
								<n-gi>
									<n-form-item label='' path='userName'>
										<n-select v-model:value='formData.tenantCode'
												  :options='optionList.tenantCode.list'
												  :loading='optionList.tenantCode.loading'
												  :disabled='optionList.tenantCode.disabled'
												  :placeholder='optionList.tenantCode.placeholder'
												  size='medium'
												  virtual-scroll filterable clearable/>
									</n-form-item>
								</n-gi>
								<n-gi>
									<n-form-item label='' path='userName'>
										<n-input
											v-model:value='formData.userName'
											size='medium' placeholder='用户名' type='text'
											clearable>
											<template v-slot:prefix>
												<i class='fa fa-user'/>
											</template>
										</n-input>
									</n-form-item>
								</n-gi>
								<n-gi>
									<n-form-item label='' path='password'>
										<n-input
											v-model:value='formData.password'
											show-password-on='click'
											size='medium' placeholder='密码' type='password'
											clearable>
											<template v-slot:prefix>
												<i class='fa fa-lock'/>
											</template>
										</n-input>
									</n-form-item>
								</n-gi>
								<n-gi>
									<n-flex justify='center'>
										<n-button :loading='loginLoading' strong
												  :bordered='false' size='medium' type='info'
												  @click='login'>
											登录
										</n-button>
										<n-button strong secondary
												  :bordered='false' size='medium' type='tertiary'
												  @click='reset'>
											重置
										</n-button>
									</n-flex>
								</n-gi>
							</n-grid>
						</n-form>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang='ts' setup>
/*分段式加载*/
import { onBeforeMount, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from '@/config/axios/index.ts';
/*图标*/
import 'font-awesome/css/font-awesome.min.css';
/*VxeTable*/
import { VxeUI } from '@/config/vxe/index.ts';
import type { Options } from '#/Options.d.ts';
import { FormInst, FormProps, FormRules, useMessage } from 'naive-ui';
import type { JsonResultProps } from '#/JsonResult.d.ts';
const router = useRouter();
const formConfig = reactive<FormProps>({
	disabled             : false,
	inline               : false,
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	showFeedback         : true,
	showLabel            : true,
	showRequireMark      : true,
	requireMarkPlacement : 'left',
	size                 : 'medium',
	validateMessages     : undefined
});
const formData = reactive({
	userName   : 'admin',
	password   : 'Admin@1234',
	deviceType : 'computer',
	userType   : 'browser_user',
	tenantCode : null as string | number | null
});
const formRules = reactive<FormRules>({
	userName : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入用户名'
	},
	password : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入密码'
	}
});
const formRef = ref<FormInst>();
// 接口下拉选
const optionList = reactive<Options>({
	tenantCode : {
		loading     : true,
		disabled    : true,
		placeholder : '请选择工作域',
		list        : [],
		map         : {}
	}
});
const loginLoading = ref(false);
const count = ref<number>(1);
onBeforeMount(() => {
	initAll();
});
const initAll = async () => {
	// 这句话是为了解决TypeScript的报错
	const _window = window as any;
	_window.$message = useMessage();
	// 请求下拉选接口的数据
	await initOptionList();
};
const initOptionList = async () => {
	loginLoading.value = true;
	axios<any, JsonResultProps<any>, any>({
		method : 'GET',
		url    : '/tenant/list',
		data   : formData
	}).then((jsonResult: JsonResultProps<any>) => {
		// 将禁用和加载状态解除
		optionList.tenantCode.list = jsonResult['data'];
		optionList.tenantCode.loading = false;
		optionList.tenantCode.disabled = false;
		// 默认选中第一行租户
		formData.tenantCode = optionList.tenantCode.list[0].value;
		loginLoading.value = false;
	}).catch((error: unknown) => {
		loginLoading.value = false;
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'getOptionException'
		});
	});
};
const login = async () => {
	loginLoading.value = true;
	sessionStorage.removeItem('x-auth-token');
	axios<any, JsonResultProps<any>, any>({
		method : 'POST',
		url    : '/auth/login',
		data   : formData
	}).then((jsonResult: JsonResultProps<any>) => {
		count.value++;
		if (jsonResult['status']) {
			sessionStorage.setItem('loginTenantCode', formData.tenantCode as string);
			if (jsonResult['isRedirect']) {
				// 用户登录成功
				// 获取到地址后通过router跳转到首页
				router.push('/index');
			}
			loginLoading.value = false;
		} else {
			loginLoading.value = false;
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'warning',
				id      : `doLoginFailed${count.value}`
			});
		}
	}).catch((error: unknown) => {
		loginLoading.value = false;
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'doLoginException'
		});
	});
};
const reset = async () => {
	// 编写一个重置表单的代码
	formRef.value?.restoreValidation();
	Object.assign(formData, {
		userName   : 'admin',
		password   : 'Admin@1234',
		deviceType : 'computer',
		userType   : 'browser_user',
		tenantCode : null
	});
	// 默认选中第一行租户
	formData.tenantCode = optionList.tenantCode.list[0].value;
};
</script>
<style lang='scss' scoped>
h4{
	font-size     :30px;
	font-weight   :unset;
	line-height   :1.5;
	margin-top    :0;
	margin-bottom :.5rem;
	color         :#CB151E;
	text-shadow   :1px 1px 6px rgba(96, 98, 102, .8);
}
.login_container{
	margin                :0;
	padding               :0;
	border                :0;
	height                :100%;
	width                 :100%;
	box-sizing            :border-box;
	overflow              :hidden;
	// background-image      :url('@/assets/login/images/bg2.jpg');
	background-attachment :fixed;
	background-repeat     :no-repeat;
	background-size       :100% 100%;
	position              :relative;
	.flex_center{
		margin          :0;
		padding         :0;
		border          :0;
		height          :100%;
		width           :100%;
		box-sizing      :border-box;
		display         :flex;
		flex-direction  :row;
		flex-wrap       :nowrap;
		align-items     :center;
		justify-content :center;
		align-content   :center;
		.login_panel{
			margin     :0;
			padding    :0;
			border     :0;
			height     :100%;
			min-width  :400px;
			width      :calc(100% - 80%);
			text-align :center;
			.flex_center{
				margin          :0;
				padding         :0;
				border          :0;
				height          :100%;
				width           :100%;
				display         :flex;
				align-items     :center;
				flex-direction  :column;
				flex-wrap       :nowrap;
				align-content   :center;
				justify-content :center;
				.login_form{
					margin           :0;
					padding          :0;
					border           :0;
					width            :100%;
					box-shadow       :1px 1px 6px 3px rgba(96, 98, 102, .8);
					background-color :rgba(255, 255, 255, .3);
					border-radius    :8px;
					display          :flex;
					align-items      :center;
					flex-direction   :column;
					flex-wrap        :nowrap;
					align-content    :center;
					justify-content  :center;
					.please_login_text{
						margin        :0;
						padding       :0;
						border        :0;
						width         :100%;
						font-size     :25px;
						color         :#4B4848;
						font-weight   :bolder;
						border-bottom :#4B4848 3px solid;
					}
					.n-form{
						box-sizing :border-box;
						margin     :0;
						padding    :2% 5% 2%;
						border     :0;
						width      :100%;
						height     :100%;
					}
				}
			}
		}
	}
}
</style>